package cn.glccc.ds.base.controller;

import cn.glccc.common.vo.Result;
import cn.glccc.ds.base.entity.BaseEntity;
import cn.glccc.ds.base.service.IBaseService;
import cn.glccc.ds.utils.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.reflect.GenericTypeUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 基类 Controller，封装了增删改查等公共接口
 *
 * @author glccc
 * @date 2024-06-07
 */
@Slf4j
public class BaseController<S extends IBaseService, T extends BaseEntity> {

    protected final Class<?>[] typeArguments = GenericTypeUtils.resolveTypeArguments(this.getClass(), BaseController.class);
    protected final Class<S> serviceClass = (Class<S>) this.typeArguments[0];
    protected final Class<T> entityClass = (Class<T>) this.typeArguments[1];

    /**
     * 泛型服务类，通过set方法注入
     */
    protected S baseService;

    @Autowired
    protected void setBaseService(ApplicationContext context) {
        if (this.baseService == null) {
            this.baseService = context.getBean(serviceClass);
        }
    }

    /**
     * 获取数据库当前时间，用于测试数据库是否正确配置
     */
    @GetMapping("/now")
    protected Result<?> now() {
        return Result.success(this.baseService.selectNow());
    }

    /**
     * 分页查询
     *
     * @param entity
     * @param page   页数current，默认1；每页数量size，默认10
     * @return
     */
    @GetMapping("/list")
    protected Result<?> list(T entity, Page<T> page) {
        QueryWrapper<T> qw = QueryGenerator.initQueryWrapper(entity);
        IPage listPage = this.baseService.page(page, qw);
        return Result.success(listPage);
    }

    /**
     * 根据id获取信息
     *
     * @param id
     * @return
     */
    @GetMapping("/info")
    protected Result<?> info(String id) {
        return Result.success(this.baseService.getById(id));
    }

    /**
     * 添加
     */
    @PostMapping("/add")
    protected Result<?> add(@RequestBody T entity) {
        return Result.success(this.baseService.save(entity));
    }

    /**
     * 修改
     *
     * @param entity id为必要参数
     */
    @PutMapping("/edit")
    protected Result<?> edit(@RequestBody T entity) {
        if (entity.getId() == null) {
            return Result.failure("id为必要参数");
        }

        boolean b = this.baseService.updateById(entity);
        if (!b) {
            return Result.failure("数据修改冲突，请刷新重试！");
        }

        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/del")
    protected Result<?> del(@RequestBody List<String> ids) {
        return Result.success(this.baseService.removeByIds(ids));
    }

}
